package com.example.hiworld;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
/*
 * https://www.jianshu.com/p/d4762b5cba79
 * https://www.jianshu.com/p/87f8ba70cf77
 *
 * */
public class MytestPlugins implements MethodChannel.MethodCallHandler {
    private static final String CHANNEL = "channel_name";
    private Context mContext;
    MethodChannel channel;
    private MytestPlugins(Context context, BinaryMessenger binaryMessenger) {
        this.mContext = context;
         channel =  new MethodChannel(binaryMessenger, CHANNEL);
        channel .setMethodCallHandler(this);
    }

    public static MytestPlugins registerWith(FlutterActivity activity, BinaryMessenger binaryMessenger) {
        return new MytestPlugins(activity, binaryMessenger);
    }

    @Override
    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
        String method = call.method;
        switch (method) {
            case "flag_name": //与Flutter中的invokeMethod传参一一对应。
                showAndroidToast();
                Log.i("flutter", "flutter调用android成功 " );
                break;
            default:
                result.notImplemented();
                break;
        }
    }

    private void showAndroidToast() {
        Toast.makeText(mContext, "第一个Flutter invoke Native", Toast.LENGTH_LONG).show();
    }

    public void invokeFlutter() {
        Log.i("flutter", "安卓调用flutter" );
        channel.invokeMethod("native-invoke-flutter", "这是native 主动调用 flutter的参数", new MethodChannel.Result() {
            @Override
            public void success(Object result) {
                Log.i("flutter", "安卓调用flutter===》后收到flutter的回复 success: result = " + result.toString());
            }

            @Override
            public void error(String errorCode, String errorMessage, Object errorDetails) {
                Log.i("flutter", "安卓调用flutter===》error==="+errorCode+"====="+errorMessage );
            }

            @Override
            public void notImplemented() {

            }
        });
    }
}

